package com.vehicle.common.util;

import com.sun.org.apache.regexp.internal.RE;
import org.apache.commons.lang3.CharEncoding;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;
import java.util.Objects;

/**
 * Created by yantingbin on 2017/7/18.
 */
public final class WebHelper {
    private static final Logger LOGGER= LoggerFactory.getLogger(WebHelper.class);

    private WebHelper() {
        throw new IllegalAccessError("Utility class");
    }

    /**
     * 获得用户远程地址
     *
     * @param request the request
     * @return the remote addr
     */
    public static String getRemoteAddr(HttpServletRequest request) {
        String remoteAddr = request.getHeader("X-Real-IP");
        if (StringHelper.isBlank(remoteAddr)) {
            remoteAddr = request.getHeader("X-Forwarded-For");
        }
        if (StringHelper.isBlank(remoteAddr)) {
            remoteAddr = request.getHeader("Proxy-Client-IP");
        }
        if (StringHelper.isBlank(remoteAddr)) {
            remoteAddr = request.getHeader("WL-Proxy-Client-IP");
        }
        return remoteAddr != null ? remoteAddr : request.getRemoteAddr();
    }

    /**
     * 是否是ajax请求
     * @param request
     * @return
     */
    public static boolean isAjax(HttpServletRequest request){
        return "XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"));
    }

    /**
     * 将request请求中的参数以及值转换成一个Map格式
     * @param request
     * @return
     */
    public static Dto getRequestMap(HttpServletRequest request){
        Dto dto=new BaseDto();
        Enumeration<?> enumeration=request.getParameterNames();
        while (enumeration.hasMoreElements()){
            String name= Objects.toString(enumeration.nextElement());
            String[] values=request.getParameterValues(name);

            Object val;
            if(values.length==1){
                val=values[0];
            }else{
                val= Arrays.asList(values);
            }
            dto.put(name,val);
        }
        return dto;
    }

    /**
     * 获取访问路径
     * @param request
     * @return
     */
    public static String getBaseURL(HttpServletRequest request){
        String path=request.getContextPath();
        return request.getScheme()+"://"
                +request.getServerName()+":"+request.getServerPort()+path+"/";
    }

    public static void out(HttpServletResponse response, Map<String,String> resultMap){

        try(PrintWriter out= response.getWriter();){
            response.setCharacterEncoding(CharEncoding.UTF_8);
            out.println(Jsons.toJson(resultMap));
        }catch (Exception e){
           LOGGER.error("invoke webhelper out method has an exception",e);
        }
    }
}
